<template>
  <div class="r-container">

    <input type="file" ref="upload" accept=".json" @change="executorListchange" id="r_file_executor"
      style="display: none;">
    <div class='r-opreation'>
      <el-tag style="margin-right: 20px;">总数：{{ tableData.length }}</el-tag>
      <el-popconfirm style="margin-left:20px" @confirm='removeSelect' confirm-button-text='确定' cancel-button-text='取消'
        icon="el-icon-info" icon-color="red" title="确认删除吗？">
        <template #reference>
          <el-button title="删除所选" type="danger" round>
            <el-icon style="margin-right: 4px;">
              <Delete />
            </el-icon>
            删除所选
          </el-button>
        </template>
      </el-popconfirm>

      <el-button style="margin-left:40px" type="primary" @click="uploadJson" round title="初始化文件">
        <el-icon style="margin-right: 4px;">
          <Document />
        </el-icon>
        初始化文件
      </el-button>
      <el-button type="primary" @click="downloadFile" round title="下载文件">
        <el-icon style="margin-right: 4px;">
          <DocumentChecked />
        </el-icon>
        下载文件
      </el-button>
      <el-button type="primary" @click="showJson" round title="查看json">
        <el-icon style="margin-right: 4px;">
          <DocumentCopy />
        </el-icon>
        查看json
      </el-button>
      <el-button v-show="!onSerach" icon="Search" circle @click="onSerach = true"></el-button>

      <el-button v-show="onSerach" class="search">
        <el-icon>
          <Search />
        </el-icon>
        <input v-model="search" placeholder="请输入分组名称">
        <el-icon @click="onSerach = false; search = ''">
          <Close />
        </el-icon>
      </el-button>

    </div>
    <div class="edit" ref="edit">
      <el-table :default-sort="{ prop: 'sortNumber', order: 'ascending' }" height='100%'
        empty-text='数据为空，请上传json，或者右侧新建'
        :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
        ref="multipleTable" tooltip-effect="dark" style="width: 100%">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column label="#" width="50">
          <template v-slot="scope">
            {{ scope.row.index = scope.$index }}
          </template>
        </el-table-column>
        <el-table-column prop="id" label="id">
        </el-table-column>
        <el-table-column prop="name" label="name" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="sortNumber" label="sortNumber" type="number" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template v-slot="scope">
            <el-button @click="handleEdit(scope.row)">编辑</el-button>
            <el-popconfirm @confirm='handleDelete(scope.row)' confirm-button-text='确定' cancel-button-text='取消'
              icon="el-icon-info" icon-color="red" title="确认删除吗？">
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="分组id">
          <el-input @keyup.enter="addRole" v-model="form.id" placeholder="分组id"></el-input>
        </el-form-item>
        <el-form-item label="分组name">
          <el-input @keyup.enter="addRole" v-model="form.name" placeholder="分组name"></el-input>
        </el-form-item>
        <el-form-item label="sortNumber">
          <el-input @keyup.enter="addRole" v-model="form.sortNumber" placeholder="sortNumber"></el-input>
        </el-form-item>
        <el-form-item v-show="editType == 'add'">
          <el-button type="primary" @click="addRole">立即创建</el-button>
          <el-button @click="resetForm()">重置</el-button>
        </el-form-item>

        <el-form-item v-show="editType == 'edit'">
          <el-button type="primary" @click="addRole">修改</el-button>
          <el-button @click="cancelEdit">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog title="json" v-model="jsonDialogShow" width="600px" center>
      <textarea class="json-txt" :value='jsonInfo'>
  </textarea>
    </el-dialog>
  </div>
</template>

<script>
import store from "../store"
import { Delete, Document, DocumentChecked, DocumentCopy, Search, Close } from '@element-plus/icons-vue'
import { ElMessage, ElNotification } from 'element-plus'
export default {
  name: "PermissionManager",
  data() {
    return {
      jsonInfo: '',
      jsonDialogShow: false,
      fileName: 'role.json',
      deleteDialogVisible: true,
      tableData: [],
      editType: 'add',
      form: {
        name: '',
        id: '',
        sortNumber: '',
        index: -1
      },
      multipleSelection: [],
      search: '',
      onSerach: false
    }
  },
  store,
  components: {
    Delete,
    Document,
    DocumentChecked,
    DocumentCopy,
    Search,
    Close
  },
  methods: {
    resetForm() {
      this.form = {
        name: '',
        id: '',
        sortNumber: '',
        index: -1
      }
    },
    removeSelect() {
      let selection = this.$refs.multipleTable.selection
      selection.sort(function (a, b) {
        return b.sortNumber - a.sortNumber;
      })
      for (let i = selection.length - 1; i >= 0; i--) {
        this.tableData.splice(selection[i].index, 1)
      }
      for (let i = 0; i < this.tableData.length; i++) {
        this.tableData[i].dataIndex = i
      }
      this.save()
      ElMessage.success('已删除')
    },
    downloadFile() {
      if (!this.tableData) {
        ElMessage.error('未初始化')
        return
      }

      function fakeClick(obj) {
        var ev = document.createEvent("MouseEvents");
        ev.initMouseEvent(
          "click",
          true,
          false,
          window,
          0,
          0,
          0,
          0,
          0,
          false,
          false,
          false,
          false,
          0,
          null
        );
        obj.dispatchEvent(ev);
      }

      function exportRaw(name, data) {
        var urlObject = window.URL || window.webkitURL || window;
        var export_blob = new Blob([data]);
        var save_link = document.createElementNS(
          "http://www.w3.org/1999/xhtml",
          "a"
        );
        save_link.href = urlObject.createObjectURL(export_blob);
        save_link.download = name;
        fakeClick(save_link);
      }

      let outJson = []
      for (let i = 0; i < this.tableData.length; i++) {
        outJson.push({
          name: this.tableData[i].name,
          id: this.tableData[i].id,
          sortNumber: this.tableData[i].sortNumber
        })
      }
      exportRaw(
        this.fileName,
        JSON.stringify(outJson, null, 4)
      );
    },
    cancelEdit() {
      this.editType = 'add'
      this.form = {
        name: '',
        id: '',
        sortNumber: '',
        index: -1
      }
    },
    save() {
      sessionStorage.setItem('gList', JSON.stringify(this.tableData))
      sessionStorage.setItem('gFileName', this.fileName)
    },
    addRole() {
      if (this.form.dataIndex !== undefined && this.form.dataIndex > -1) {
        for (let i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].id == this.form.id && i != this.form.dataIndex) {
            ElMessage.error('id已存在')
            return
          } else if (this.tableData[i].name == this.form.name && i != this.form.dataIndex) {
            ElMessage.error('name已存在')
            return
          } else if (this.tableData[i].sortNumber == this.form.sortNumber && i != this.form.dataIndex) {
            ElMessage.error('sortNumber已存在')
            return
          }
        }

        this.$set(this.tableData, this.form.dataIndex, {
          name: this.form.name,
          id: this.form.id,
          sortNumber: parseInt(this.form.sortNumber),
          dataIndex: this.form.dataIndex
        })
      } else {
        if (!this.form.id) {
          ElMessage.error('id必填')
          return
        }
        if (!this.form.name) {
          ElMessage.error('name必填')
          return
        }

        if (!this.form.sortNumber) {
          ElMessage.error('sortNumber必填')
          return
        }

        for (let i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].id == this.form.id) {
            ElMessage.error('id已存在')
            return
          } else if (this.tableData[i].name == this.form.name) {
            ElMessage.error('name已存在')
            return
          } else if (this.tableData[i].sortNumber == this.form.sortNumber) {
            ElMessage.error('sign已存在')
            return
          }
        }
        this.tableData.push({
          name: this.form.name,
          id: this.form.id,
          sortNumber: parseInt(this.form.sortNumber),
          dataIndex: this.tableData.length
        })
      }

      this.save();
      ElNotification({
        message: '操作成功',
        position: 'top-right',
        type: 'success'
      })
    },
    uploadJson() {
      var inputObj = document.querySelector(
        "#r_file_executor"
      );
      inputObj.click();
    },
    executorListchange() {
      var files = document.querySelector("#r_file_executor").files
      let file = files[0]
      if (file.name.indexOf(".json") != file.name.length - 5) {
        ElMessage.error('不支持的文件格式')
        return;
      }

      var reader = new FileReader(); //新建一个FileReader
      reader.readAsText(file, "UTF-8"); //读取文件
      reader.onload = (evt) => {
        let roles = JSON.parse(evt.target.result)
        if (roles instanceof Array) {
          if (roles.length == 0 || roles[0].name === undefined || roles[0].id === undefined || roles[0].sortNumber === undefined) {
            ElMessage.error('格式有误')
            return
          }
          //this.tableData = roles

          this.tableData.splice(0, this.tableData.length)
          for (let x = 0; x < roles.length; x++) {
            this.tableData.push({
              name: roles[x].name,
              id: roles[x].id,
              sortNumber: roles[x].sortNumber,
              dataIndex: x
            })
          }
        } else {
          this.$message.error('格式有误');
        }
        this.fileName = file.name
        this.save();
        document.querySelector("#r_file_executor").value = ''
      }
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.editType = 'edit';
    },
    handleDelete(row) {
      this.deleteDialogVisible = false
      this.tableData.splice(row.dataIndex, 1)
      for (let i = 0; i < this.tableData.length; i++) {
        this.tableData[i].dataIndex = i
      }
      this.save()
      this.$message({
        message: '已删除',
        type: 'success'
      });
    },
    fakeClick(obj) {
      var ev = document.createEvent("MouseEvents");
      ev.initMouseEvent(
        "click",
        true,
        false,
        window,
        0,
        0,
        0,
        0,
        0,
        false,
        false,
        false,
        false,
        0,
        null
      );
      obj.dispatchEvent(ev);
    }, showJson() {
      if (!this.tableData) {
        ElMessage.error('未初始化')
        return
      }
      let outJson = []
      for (let i = 0; i < this.tableData.length; i++) {
        outJson.push({
          name: this.tableData[i].name,
          id: this.tableData[i].id,
          sortNumber: this.tableData[i].sortNumber
        })
      }
      this.jsonInfo = JSON.stringify(outJson, null, 4)
      this.jsonDialogShow = true
    }
  },
  computed: {},
  mounted() {
    if (sessionStorage.getItem('gList')) {
      this.tableData = JSON.parse(sessionStorage.getItem('gList'))
      this.fileName = sessionStorage.getItem('gFileName')
    }

  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.r-container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.json-txt {
  resize: none;
  width: 100%;
  height: 600px;
  border: none;
  outline: none;
}

.json-txt:hover {
  border: none;
  outline: none;
}

.r-container .r-opreation {
  text-align: left;
  margin-bottom: 10px;
}

.r-container .r-opreation .search {
  margin-left: 10px;
  display: inline-flex;
  align-items: center;
  padding: 0 14px;
  border-radius: 40px;
}

.r-container .r-opreation .search input {
  border: none;
  outline: none;
  background-color: transparent;
  margin-left: 4px;
}

.r-container .r-opreation .search i {
  color: rgba(143, 143, 143, 0.933);
}

.r-container .r-opreation .search .el-icon-close {
  cursor: pointer;
}

.r-container .r-opreation .search .el-icon-close:hover {
  color: #f56c6c;
}

.r-container .r-opreation .search:hover {
  border: 1px #bcdeff solid;
}

.r-container .edit {
  display: flex;
  height: 10px;
  flex: 1;
}

.r-container .edit .el-table {
  flex: 1;
}

.r-container .edit .el-form {
  width: 300px;
  margin-left: 40px;
}
</style>
